package com.idroc.message.filter.codec;

import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import com.idroc.message.Message;

/**
 * 多路复用编码器
 * @author 赤脚詹(yuyoo4j@163.com)
 * @date Aug 17, 2009 4:13:49 PM 
 * @memo:
 */
public class MessageEncoder implements ProtocolEncoder {
	
	// private static final Logger log = LoggerFactory.getLogger(MessageEncoder.class);
	
	/**
	 * 消息通讯版本
	 */
	private static final byte MSG_COMMUNICATION_VERSION = (byte)1;

	public void dispose(IoSession iosession) throws Exception {

	}
	
	/**
	 * 编码
	 */
	public void encode(IoSession iosession, Object obj,
			ProtocolEncoderOutput output) throws Exception {
				
		ByteBuffer ob = ByteBuffer.allocate(512).setAutoExpand(true);
		// 跳过头部字节
		ob.position(5);
		Message msg = (Message)obj; 
		msg.encode(ob);  // 消息编码	
		int totalLength = ob.position();  // 获取消息总长度
		ob.flip();
		// 写入消息头部字节
		ob.put(MSG_COMMUNICATION_VERSION); // 写入消息版本
		ob.putInt(totalLength - 5); // 重新写入消息总长度
		ob.rewind();
		output.write(ob);
	}

}
